<script setup lang="ts">
import CustomNavbar from '@/pages/index/components/CustomNavbar.vue'
import Swiper from '@/components/Swiper.vue'
import { getHomeBanner, getHomeCategory, getHomeHotPanel } from '@/api/home'
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'
import type { BannerItem, CategoryItem, HotPanelItem } from '@/types/home'
import CategoryPanel from '@/pages/index/components/CategoryPanel.vue'
import HotPanel from '@/pages/index/components/HotPanel.vue'
import GuessLike from '@/components/GuessLike.vue'
import PageSkeleton from '@/pages/index/components/PageSkeleton.vue'

const bannerList = ref<BannerItem[]>([])
const categoryList = ref<CategoryItem[]>([])
const hotPanelList = ref<HotPanelItem[]>([])

// 猜你喜欢-组件实例
const guessRef = ref<InstanceType<typeof GuessLike>>()

// 刷新效果
const isTriggered = ref(false)

// 加载效果
const isLoading = ref(false)

// 滚动触底事件-滚动触底获取分页
function onScrolltolower() {
  guessRef.value?.getGuessYouLike()
}

// 自定义下拉刷新触发
async function onRefresherRefresh() {
  // 加载效果
  isTriggered.value = true

  // 重置-猜你喜欢数据
  guessRef.value?.resetData()
  // 同时加载数据
  await Promise.all([
    fetchBanner(),
    fetchCategory(),
    fetchHotPanel(),
    // 再获取-猜你喜欢数据
    guessRef.value?.getGuessYouLike(),
  ])
  isTriggered.value = false
}

// 获取首页轮播图
async function fetchBanner() {
  const res = await getHomeBanner()
  console.log('首页轮播数据：', res)
  bannerList.value = res.result
}

// 获取首页分类
async function fetchCategory() {
  const res = await getHomeCategory()
  console.log('首页分类数据：', res)
  categoryList.value = res.result
}

// 获取热门推荐
async function fetchHotPanel() {
  const res = await getHomeHotPanel()
  console.log('首页推荐数据：', res)
  hotPanelList.value = res.result
}

// 挂载
onLoad(async () => {
  isLoading.value = true
  await Promise.all([fetchBanner(), fetchCategory(), fetchHotPanel()])
  isLoading.value = false
})
</script>

<template>
  <!-- 顶部导航栏 -->
  <CustomNavbar />
  <!-- 首页内容 -->
  <scroll-view
    refresher-enabled
    @refresherrefresh="onRefresherRefresh"
    :refresher-triggered="isTriggered"
    @scrolltolower="onScrolltolower"
    class="scroll-view"
    scroll-y
  >
    <!-- 骨架屏 -->
    <PageSkeleton v-if="isLoading" />
    <template v-else>
      <!-- 轮播图 -->
      <Swiper style="height: 150px" :list="bannerList" />
      <!-- 主页分类 -->
      <CategoryPanel :list="categoryList" />
      <!-- 热门商品 -->
      <HotPanel :list="hotPanelList" />
      <!-- 猜你喜欢 -->
      <GuessLike ref="guessRef" />
    </template>
  </scroll-view>
</template>

<style lang="scss">
// 类似于网页body标签的样式
page {
  background-color: #f7f7f7;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.scroll-view {
  flex: 1;
}
</style>
